from django.core.management.base import BaseCommand
from django.core.mail import send_mail
from django.conf import settings
from django.contrib.auth.models import User
from spare_parts.models import SparePart

class Command(BaseCommand):
    help = '检查库存状态并发送预警通知'

    def add_arguments(self, parser):
        parser.add_argument(
            '--email',
            action='store_true',
            help='发送邮件通知',
        )
        parser.add_argument(
            '--recipients',
            type=str,
            help='邮件接收者（逗号分隔的邮箱地址）',
        )

    def handle(self, *args, **options):
        # 获取库存不足的备件
        low_stock_parts = []
        over_stock_parts = []
        
        for part in SparePart.objects.filter(status='active'):
            if part.is_low_stock():
                low_stock_parts.append(part)
            elif part.is_over_stock():
                over_stock_parts.append(part)
        
        # 生成报告
        report = self.generate_report(low_stock_parts, over_stock_parts)
        
        # 输出到控制台
        self.stdout.write(report)
        
        # 如果需要发送邮件
        if options['email']:
            self.send_email_notification(report, options['recipients'])

    def generate_report(self, low_stock_parts, over_stock_parts):
        report_lines = []
        
        if low_stock_parts:
            report_lines.append("⚠️ 库存不足预警：")
            for part in low_stock_parts:
                report_lines.append(
                    f"  - {part.part_number} - {part.name} "
                    f"(当前: {part.current_stock} {part.unit}, "
                    f"最低: {part.min_stock} {part.unit})"
                )
            report_lines.append("")
        
        if over_stock_parts:
            report_lines.append("📦 库存过高预警：")
            for part in over_stock_parts:
                report_lines.append(
                    f"  - {part.part_number} - {part.name} "
                    f"(当前: {part.current_stock} {part.unit}, "
                    f"最高: {part.max_stock} {part.unit})"
                )
            report_lines.append("")
        
        if not low_stock_parts and not over_stock_parts:
            report_lines.append("✅ 所有备件库存状态正常")
        
        return "\n".join(report_lines)

    def send_email_notification(self, report, recipients=None):
        if not recipients:
            # 默认发送给管理员用户
            admin_users = User.objects.filter(is_staff=True, is_active=True)
            recipients = [user.email for user in admin_users if user.email]
        
        if not recipients:
            self.stdout.write(self.style.WARNING('没有找到有效的邮件接收者'))
            return
        
        if isinstance(recipients, str):
            recipients = [email.strip() for email in recipients.split(',')]
        
        subject = '备件库存预警通知'
        message = f"""
备件库存状态检查报告：

{report}

请及时处理相关备件的库存问题。

此邮件由系统自动发送，请勿直接回复。
"""
        
        try:
            send_mail(
                subject=subject,
                message=message,
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=recipients,
                fail_silently=False,
            )
            self.stdout.write(self.style.SUCCESS(f'成功发送邮件给: {", ".join(recipients)}'))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'发送邮件失败: {e}'))
